//
//  HANetworkRequest.m
//  HAFund
//
//  Created by 夏成龙 on 2018/10/30.
//  Copyright © 2018年 夏成龙. All rights reserved.
//

#import "HANetworkRequest.h"
#import <AFNetworking.h>
#import "FactoryClass.h"

NSInteger const kRequestUrlTimeOut = 10.0f;

@interface HANetworkRequest ()

@property (strong, nonatomic) AFHTTPSessionManager *sessionMgr;


@end

@implementation HANetworkRequest

+ (instancetype)requestManager {
    static HANetworkRequest *requestManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        requestManager = [[self alloc] init];
        [requestManager sessionMgr];
    });
    return requestManager;
}

- (AFHTTPSessionManager *)sessionMgr {
    if (!_sessionMgr) {
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        _sessionMgr = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
        _sessionMgr.requestSerializer = [AFHTTPRequestSerializer serializer];
        _sessionMgr.requestSerializer.timeoutInterval = kRequestUrlTimeOut;
        
#if ((defined DEBUG) || (defined ENTERPRISE))
        AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
        [securityPolicy setAllowInvalidCertificates:YES];
        [securityPolicy setValidatesDomainName:NO];
        _sessionMgr.securityPolicy = securityPolicy;
#endif
        _sessionMgr.responseSerializer = [AFHTTPResponseSerializer serializer];
        _sessionMgr.responseSerializer.acceptableContentTypes =
        [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    }
    return _sessionMgr;
}

+ (NSURLSessionDataTask *)callRequest:(HARequest *)request callBlock:(HARequestResponseBlock)responseBlock {

    // 设置请求头
   [HANetworkRequest requestManager].sessionMgr.requestSerializer = request.requestHead;
   NSURLSessionDataTask *dataTask = [[HANetworkRequest requestManager].sessionMgr dataTaskWithRequest:request.request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
       if (error && error.code == NSURLErrorCancelled) {
           return ;
       } else if (responseBlock) {
           responseBlock(response, responseObject, error);
       }
   }];
    request.task = dataTask;
    [dataTask resume];
    return dataTask;
}
@end
